from typing import List, Dict, Any
from fastapi import APIRouter, Depends, HTTPException, status, Query
from sqlalchemy.orm import Session

from app.core.database.connection import get_database
from app.domains.device.services import DeviceService
from app.domains.models import SensorData, Device
from app.shared.schemas.response import success_response, paginated_response, error_response
from app.shared.constants.status_codes import BusinessCode
from app.api.dependencies import get_current_user
from app.shared.constants.enums import SensorType
from datetime import datetime, timedelta
import logging

logger = logging.getLogger(__name__)

router = APIRouter(prefix="/sensors", tags=["传感器数据"])


@router.get("/data", response_model=dict, summary="获取传感器数据")
async def get_sensor_data(
    device_id: int = Query(..., description="设备ID"),
    sensor_type: str = Query(None, description="传感器类型"),
    start_time: datetime = Query(None, description="开始时间"),
    end_time: datetime = Query(None, description="结束时间"),
    page: int = Query(1, ge=1, description="页码"),
    page_size: int = Query(100, ge=1, le=1000, description="每页数量"),
    current_user: dict = Depends(get_current_user),
    db: Session = Depends(get_database)
):
    """
    获取传感器数据（所有用户可查看）
    
    - **device_id**: 设备ID
    - **sensor_type**: 传感器类型（可选）
    - **start_time**: 开始时间（可选）
    - **end_time**: 结束时间（可选）
    - **page**: 页码
    - **page_size**: 每页数量
    """
    try:
        # 验证设备是否存在
        device = db.query(Device).filter(Device.id == device_id).first()
        if not device:
            return error_response(
                message="设备不存在",
                code=BusinessCode.DATA_NOT_FOUND
            )
        
        # 构建查询
        q = db.query(SensorData).filter(SensorData.device_id == device_id)
        
        # 传感器类型筛选
        if sensor_type:
            q = q.filter(SensorData.data_type == sensor_type)
        
        # 时间范围筛选
        if start_time:
            q = q.filter(SensorData.timestamp >= start_time)
        
        if end_time:
            q = q.filter(SensorData.timestamp <= end_time)
        
        # 按时间倒序排列
        q = q.order_by(SensorData.timestamp.desc())
        
        # 获取总数
        total = q.count()
        
        # 分页
        offset = (page - 1) * page_size
        sensor_data = q.offset(offset).limit(page_size).all()
        
        # 转换为响应格式
        data_list = [
            {
                "id": data.id,
                "device_id": data.device_id,
                "timestamp": data.timestamp,
                "data_type": data.data_type,
                "value": data.value,
                "unit": data.unit,
                "quality": data.quality,
                "created_at": data.created_at
            }
            for data in sensor_data
        ]
        
        return paginated_response(
            items=data_list,
            total=total,
            page=page,
            page_size=page_size,
            message="查询成功"
        )
        
    except Exception as e:
        logger.error(f"❌ 获取传感器数据异常: {e}")
        return error_response(
            message="获取传感器数据失败",
            code=BusinessCode.OPERATION_FAILED
        )


@router.get("/latest", response_model=dict, summary="获取设备最新传感器数据")
async def get_latest_sensor_data(
    device_id: int = Query(..., description="设备ID"),
    current_user: dict = Depends(get_current_user),
    db: Session = Depends(get_database)
):
    """
    获取设备最新传感器数据（所有用户可查看）
    
    返回该设备每种传感器类型的最新数据
    """
    try:
        # 验证设备是否存在
        device = db.query(Device).filter(Device.id == device_id).first()
        if not device:
            return error_response(
                message="设备不存在",
                code=BusinessCode.DATA_NOT_FOUND
            )
        
        # 获取每种传感器类型的最新数据
        from sqlalchemy import func
        
        # 获取该设备所有传感器类型
        sensor_types = db.query(SensorData.data_type).filter(
            SensorData.device_id == device_id
        ).distinct().all()
        
        latest_data = {}
        for (sensor_type,) in sensor_types:
            latest = db.query(SensorData).filter(
                SensorData.device_id == device_id,
                SensorData.data_type == sensor_type
            ).order_by(SensorData.timestamp.desc()).first()
            
            if latest:
                latest_data[sensor_type] = {
                    "id": latest.id,
                    "timestamp": latest.timestamp,
                    "value": latest.value,
                    "unit": latest.unit,
                    "quality": latest.quality
                }
        
        return success_response(
            data={
                "device_id": device_id,
                "device_code": device.device_code,
                "device_name": device.device_name,
                "sensor_data": latest_data
            },
            message="查询成功"
        )
        
    except Exception as e:
        logger.error(f"❌ 获取最新传感器数据异常: {e}")
        return error_response(
            message="获取最新传感器数据失败",
            code=BusinessCode.OPERATION_FAILED
        )


@router.get("/statistics", response_model=dict, summary="获取传感器数据统计")
async def get_sensor_statistics(
    device_id: int = Query(..., description="设备ID"),
    sensor_type: str = Query(..., description="传感器类型"),
    start_time: datetime = Query(None, description="开始时间"),
    end_time: datetime = Query(None, description="结束时间"),
    current_user: dict = Depends(get_current_user),
    db: Session = Depends(get_database)
):
    """
    获取传感器数据统计（所有用户可查看）
    
    返回指定时间范围内传感器数据的统计信息（最大值、最小值、平均值等）
    """
    try:
        # 验证设备是否存在
        device = db.query(Device).filter(Device.id == device_id).first()
        if not device:
            return error_response(
                message="设备不存在",
                code=BusinessCode.DATA_NOT_FOUND
            )
        
        # 设置默认时间范围（最近24小时）
        if not end_time:
            end_time = datetime.utcnow()
        if not start_time:
            start_time = end_time - timedelta(hours=24)
        
        # 构建查询
        q = db.query(SensorData).filter(
            SensorData.device_id == device_id,
            SensorData.data_type == sensor_type,
            SensorData.timestamp >= start_time,
            SensorData.timestamp <= end_time
        )
        
        # 获取统计数据
        from sqlalchemy import func
        
        stats_query = db.query(
            func.count(SensorData.value).label('count'),
            func.avg(SensorData.value).label('avg_value'),
            func.min(SensorData.value).label('min_value'),
            func.max(SensorData.value).label('max_value')
        ).filter(
            SensorData.device_id == device_id,
            SensorData.data_type == sensor_type,
            SensorData.timestamp >= start_time,
            SensorData.timestamp <= end_time
        ).first()
        
        # 获取最新数据点
        latest_data = q.order_by(SensorData.timestamp.desc()).first()
        
        statistics = {
            "device_id": device_id,
            "device_code": device.device_code,
            "device_name": device.device_name,
            "sensor_type": sensor_type,
            "time_range": {
                "start_time": start_time,
                "end_time": end_time
            },
            "data_count": stats_query.count if stats_query else 0,
            "avg_value": round(float(stats_query.avg_value), 2) if stats_query.avg_value else None,
            "min_value": float(stats_query.min_value) if stats_query.min_value else None,
            "max_value": float(stats_query.max_value) if stats_query.max_value else None,
            "latest_value": float(latest_data.value) if latest_data else None,
            "latest_timestamp": latest_data.timestamp if latest_data else None,
            "unit": latest_data.unit if latest_data else None
        }
        
        return success_response(
            data=statistics,
            message="查询成功"
        )
        
    except Exception as e:
        logger.error(f"❌ 获取传感器数据统计异常: {e}")
        return error_response(
            message="获取传感器数据统计失败",
            code=BusinessCode.OPERATION_FAILED
        )


@router.get("/types", response_model=dict, summary="获取传感器类型列表")
async def get_sensor_types(
    current_user: dict = Depends(get_current_user),
    db: Session = Depends(get_database)
):
    """
    获取系统支持的传感器类型列表（所有用户可查看）
    """
    try:
        sensor_types = [
            {
                "type": SensorType.DOOR_SENSOR.value,
                "name": "门锁状态传感器",
                "description": "检测厕所门锁开关状态"
            },
            {
                "type": SensorType.WATER_LEVEL.value,
                "name": "水箱液位传感器",
                "description": "检测水箱液位高度"
            },
            {
                "type": SensorType.WASTE_LEVEL.value,
                "name": "污物箱液位传感器",
                "description": "检测污物箱液位高度"
            },
            {
                "type": SensorType.PAPER_LEVEL.value,
                "name": "纸巾余量传感器",
                "description": "检测纸巾剩余量"
            },
            {
                "type": SensorType.SOAP_LEVEL.value,
                "name": "洗手液余量传感器",
                "description": "检测洗手液剩余量"
            },
            {
                "type": SensorType.TEMPERATURE.value,
                "name": "温度传感器",
                "description": "检测环境温度"
            },
            {
                "type": SensorType.HUMIDITY.value,
                "name": "湿度传感器",
                "description": "检测环境湿度"
            },
            {
                "type": SensorType.OCCUPANCY.value,
                "name": "人体感应传感器",
                "description": "检测是否有人使用"
            },
            {
                "type": SensorType.BATTERY_LEVEL.value,
                "name": "电池电量传感器",
                "description": "检测设备电池电量"
            }
        ]
        
        return success_response(
            data=sensor_types,
            message="查询成功"
        )
        
    except Exception as e:
        logger.error(f"❌ 获取传感器类型列表异常: {e}")
        return error_response(
            message="获取传感器类型列表失败",
            code=BusinessCode.OPERATION_FAILED
        )